import { createContext, useReducer } from 'react'
import reducer, { TReduceActions } from './reducer'
import {
	DEFAULT_ITEMS_PER_PAGE,
	DEFAULT_PAGE,
} from '../components/cardlist/pagination'

export type TContext = {
	state: TState
	dispatch: React.Dispatch<TReduceActions>
}

export type TCatalogData = {
	_id: string
	pictures: string
	discount: number
	price: number
	wight: string
	name: string
	likes: string[]
}

export type TProductData = {
	discount: number
	stock: number
	available: boolean
	pictures: string
	likes: string[]
	reviews: {
		rating: number
		_id: string
		text: string
		author: {
			name: string
			about: string
			avatar: string
			_id: string
			group: string
			email: string
			__v: number
		}[]
		product: string
		created_at: string
		updated_at: string
		__v: number
	}[]
	tags: string[]
	isPublished: boolean
	_id: string
	name: string
	author: {
		name: string
		about: string
		avatar: string
		_id: string
		email: string
		group: string
		__v: number
	}
	price: number
	description: string
	created_at: string
	updated_at: string
	__v: number
} | null

export type TUser = {
	_id: string
	name: string
	about: string
	avatar: string
	email: string
	password: string
	isAdmin: boolean
	group: string
}

const initialState = {
	user: {
		_id: '648cbf01e0bf2c519befb5f8',
		name: 'Максим',
		about: 'Наставник',
		avatar: 'https://i.pravatar.cc/150?img=3',
		email: 'user@yandex.ru',
		password: 'somestrongpassword',
		isAdmin: true,
		group: 'group-11',
	},
	// все данные - костыль, чтобы посчитать лайкнутые товары
	allData: [],
	// данные на странице каталога
	catalogData: [],
	// данные для карточки продукта
	productData: null,
	pending: true,
	search: '',
	sortBy: '',
	pagination: {
		itemsPerPage: DEFAULT_ITEMS_PER_PAGE,
		selectedPage: DEFAULT_PAGE,
		maxPage: DEFAULT_PAGE,
	},
}

export type TState = {
	user: TUser
	allData: TCatalogData[]
	catalogData: TCatalogData[]
	productData: TProductData
	pending: boolean
	search: string
	sortBy: string
	pagination: {
		itemsPerPage: number
		selectedPage: number
		maxPage: number
	}
}

export const AppContext = createContext<TContext>({
	state: initialState,
	dispatch: () => null,
})

type TProviderProps = {
	children: React.ReactNode
}

export const Provider = ({ children }: TProviderProps) => {
	const [state, dispatch] = useReducer(reducer, initialState)

	return (
		<AppContext.Provider value={{ state, dispatch }}>
			{children}
		</AppContext.Provider>
	)
}
